package com.example.demo.service.Impl;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Mapper.UserMapper;
import com.example.demo.dto.UserLoginDto;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginDto login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_number", user.getAccountNumber());
        queryWrapper.eq("password", user.getPassword());

        final User user1 = userMapper.selectOne(queryWrapper);
        UserLoginDto userLoginDto = new UserLoginDto();
        if(user1 != null) {
            StpUtil.login(user1.getId());
            userLoginDto.setUserName(user1.getUserName());
            userLoginDto.setToken(StpUtil.getTokenValue());
            userLoginDto.setImgUrl(user1.getImgUrl());
            userLoginDto.setId(user1.getId());
        }

        return user1 != null ? userLoginDto : null;
    }

    @Override
    public int unLogin(String id) {
        try {
            StpUtil.logout(id);
            return 1;
        } catch (Exception exception) {
            return 0;
        }

    }

    @Override
    public List<User> selectAll(String userName, String accountNumber) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name", userName);
        queryWrapper.like("account_number", accountNumber);
        final List<User> users = userMapper.selectList(queryWrapper);

        return users;
    }

    @Override
    public int update(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        final int update = userMapper.update(user, queryWrapper);
        return update;
    }

    @Override
    public int delete(int id) {
        final int i = userMapper.deleteById(id);
        return i;
    }

    @Override
    public int add(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        final int insert = userMapper.insert(user);
        return insert;
    }
}
